<template>
    <div>
        <div class="n-layout-page-header">
            <n-card :bordered="false">
                <n-space vertical justify="center">
                    <n-steps :current="currentTab" :status="currentStatus">
                        <n-step title="基本信息" description="填写流程模型基本信息" />
                        <n-step title="流程表单设计" description="设计流程表单" />
                        <n-step title="流程设计" description="设计流程" />
                        <n-step title="完成" description="恭喜您完成流程设计" />
                    </n-steps>
                </n-space>
            </n-card>
        </div>

        <n-card :bordered="false" class="mt-4 proCard">
            <div class="base-form" v-if="currentTab === 1" @next-step="nextStep">
                <div class="base-form-item">
                    <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120"
                        class="py-4" style="width: 100%;">
                        <n-form-item label="流程模型图标" path="flowModelIcon">
                            <n-popover placement="bottom" trigger="click" @update:show="handleUpdateShow">
                                <template #trigger>
                                    <n-avatar class="flowModelIcon" round :size="48" :src="fromValues.flowModelIcon" />
                                </template>
                                <n-grid :x-gap="12" :y-gap="8" :cols="4">
                                    <n-grid-item v-for="item in flowIcon" :key="item.name">
                                        <n-avatar @click="cheangeIcon(item.icon)" class="flowModelIcon" round :size="48"
                                            :src="item.icon" />
                                    </n-grid-item>
                                </n-grid>
                            </n-popover>
                        </n-form-item>
                        <n-form-item label="流程模型名称" path="flowModelName">
                            <n-input maxlength="100" show-count placeholder="请输入流程模型名称"
                                v-model:value="fromValues.flowModelName" />
                        </n-form-item>
                        <n-form-item label="流程模型分组" path="flowModelGroup">
                            <n-select v-model:value="fromValues.flowModelGroup" placeholder="请选择流程模型分组"
                                :options="groupOptions" />
                        </n-form-item>
                        <n-form-item label="流程模型类型" path="flowModelType">
                            <n-select v-model:value="fromValues.flowModelType" placeholder="请选择流程模型类型"
                                :options="typeOptions" />
                        </n-form-item>
                        <n-form-item label="流程模型说明" path="flowModelDesc">
                            <n-input maxlength="300" show-count type="textarea" :autosize="{
                                minRows: 3,
                                maxRows: 5
                            }" v-model:value="fromValues.flowModelDesc" filterable placeholder="请输入流程模型说明" />
                        </n-form-item>
                    </n-form>
                </div>

            </div>
            <div v-if="currentTab === 2" @next-step="nextStep" @prevStep="prevStep">
                <div style="height: 65vh;">
                    <FormDesign ref="childRef" />
                </div>
                <!-- <GenerateForm ref="generateFormRef" :data="widgetForm" /> -->
                <!-- <n-button type="primary" @click="handleSubmit">提交</n-button> -->
            </div>
            <div v-if="currentTab === 3" @next-step="nextStep" @prevStep="prevStep">
                <flowDesign ref="flowDesignRef" :flowData="fromValues.flowData"/>
            </div>
            <div v-if="currentTab === 4" @prev-step="prevStep" @finish="finish">
                <n-result status="success" title="操作成功" description="流程已发布" class="step-result">
                    <template #footer>
                        <div class="flex justify-center">
                            <n-button type="primary" @click="navigateToRoute">返回流程模型列表</n-button>
                        </div>
                    </template>
                </n-result>
            </div>
            <div class="flex justify-center" style="margin-top: 15px;">
                <n-space>
                    <n-button v-if="currentTab !== 4 && currentTab !== 3" type="primary" @click="nextStep">下一步</n-button>
                    <n-button v-if="currentTab === 3" type="primary" @click="nextStep"
                        :loading="formBtnLoading">提交并发布</n-button>
                    <n-button v-if="currentTab !== 1 && currentTab !== 4" @click="prevStep">上一步</n-button>
                </n-space>
            </div>
        </n-card>
    </div>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { type FormRules, useMessage } from 'naive-ui';
import flowDesign from '../flowDesign.vue';
import FormDesign from '@/components/naiveui/FormDesign.vue';
import { page } from '@/api/flow/flowGroup';
import { save, update } from '@/api/flow/flowModel';
import { ResultEnum } from '@/enums/httpEnum';
import { detail } from '@/api/flow/flowModel';
const message = useMessage();
const childRef = ref<any>(null);
const flowDesignRef = ref<InstanceType<typeof flowDesign> | null>(null);
// import GenerateForm from '../../../components/naiveui/components/generate/GenerateForm.vue';
const formRef: any = ref(null);
const currentTab = ref(1);
const currentStatus = ref<string>('process');
const router = useRouter();
const groupOptions = ref([]);
const typeOptions = ref([{ label: '工作流', value: 1 }, { label: '协同作战任务', value: 2 }]);
const popoverShow = ref<boolean>(false);
const flowIcon = ref([{ name: '工作', icon: 'https://qxht.xiaomy.net/file/icon/flow/flowTask.png' },
{ name: '任务', icon: 'https://qxht.xiaomy.net/file/icon/flow/flowHb.png' }]);
const formBtnLoading = ref<boolean>(false);
const defaultValueRef = () => ({
    // 流程模型名称
    flowModelName: '',
    // 流程模型说明
    flowModelDesc: '',
    // 流程模型分组
    flowModelGroup: null,
    // 流程模型类型
    flowModelType: null,
    // 流程模型动态表单
    flowModelForm: '',
    // 流程数据
    flowData: '',
    // 流程图标
    flowModelIcon: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'
});
let fromValues = reactive(defaultValueRef());
const rules: FormRules = {
    flowModelName: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入流程模型名称',
    },
    flowModelGroup: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型分组',
    },
    flowModelAdmin: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型管理员',
    },
    flowModelType: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择流程模型类型',
    },
};
const getFormJson = () => {
    const data = childRef?.value?.getJson();
    console.log('datadata', JSON.stringify(data));
    fromValues = Object.assign(fromValues, { flowModelForm: JSON.stringify(data) });
}
/**
 * 修改流程模型数据时设置动态表单数据
 */
const setFormJson = () => {
    message.loading('表单初始化中...', {
        duration: 500,
        onAfterLeave: async () => {
            if (currentTab.value === 2 && childRef?.value !== null) {
                childRef?.value?.setJson(JSON.parse(fromValues.flowModelForm));
            }
        }
    })
}
/**
 * 提交表单
 */
const submitForm = async () => {
    graphData();
    console.log('fromValues', fromValues);
    formBtnLoading.value = true;
    const id = router.currentRoute.value.params.id;
    const data = id === '0'?await save(fromValues):await update(fromValues);
    if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
        formBtnLoading.value = false;
    }
    if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        formBtnLoading.value = false;
    }
}
const graphData = () => {
    const data = flowDesignRef?.value?.getGraphData();
    console.log('graphData', data);
    fromValues = Object.assign(fromValues, { flowData: JSON.stringify(data) });
}
// const generateFormRef = ref(null);
// const widgetForm = {
//     "list": [
//         {
//             "label": "文本输入",
//             "type": "input",
//             "options": {
//                 "change": "",
//                 "width": "100%",
//                 "type": "text",
//                 "showLabel": true,
//                 "defaultValue": "",
//                 "placeholder": "",
//                 "maxlength": null,
//                 "showCount": false,
//                 "prefix": "",
//                 "suffix": "",
//                 "disabled": false,
//                 "allowClear": false,
//                 "readonly": false,
//                 "round": false,
//                 "rules": {
//                     "trigger": "blur",
//                     "enum": "",
//                     "message": "",
//                     "pattern": "",
//                     "required": false,
//                     "type": "string"
//                 }
//             },
//             "key": "b3354ee9074c491c9098b4e86fb19989",
//             "model": "input_b3354ee9074c491c9098b4e86fb19989",
//             "rules": []
//         }
//     ],
//     "config": {
//         "size": "medium",
//         "hideRequiredMark": false,
//         "groupType": "radioGroup",
//         "inline": false,
//         "labelAlign": "left",
//         "labelWidth": "auto",
//         "labelPlacement": "top",
//         "showLabel": true
//     }
// }
// const handleSubmit = () => {
//     generateFormRef.value?.getData().then(data => {
//         console.log(data)
//         // data success
//         // data 表单数据
//     }).catch(error => {
//         // data failed
//     })
// }
const nextStep = () => {
    if (currentTab.value === 1) {
        formRef.value.validate(async (errors) => {
            if (!errors) {
                currentTab.value += 1;
                const id = router.currentRoute.value.params.id;
                if (id !== '0') {
                    setFormJson();
                }
            }
        });
    } else if (currentTab.value === 2) {
        getFormJson();
        currentTab.value += 1;
    } else if (currentTab.value === 3) {
        submitForm();
        currentTab.value += 1;
    }
}

const prevStep = () => {
    if (currentTab.value > 1) {
        currentTab.value -= 1;
        if(currentTab.value === 2){
            setFormJson();
        }
    }
}

const finish = () => {
    currentTab.value = 1;
}
const navigateToRoute = () => {
    router.go(-1);
}
const cheangeIcon = (icon: string) => {
    fromValues.flowModelIcon = icon;
}
const handleUpdateShow = () => {
    popoverShow.value = !popoverShow.value;
}
onMounted(async () => {
    const group = await page({});
    groupOptions.value = group.records.map(item => ({ label: item.groupName, value: item.id }));
    const id = router.currentRoute.value.params.id;
    if (id !== '0') {
        const flow = await detail({ id: id });
        fromValues = Object.assign(fromValues, flow);
    }
})
</script>
<style scoped>
.base-form {
    display: flex;
    justify-content: center;
}

.base-form-item {
    width: 30%;
}

.flowModelIcon:hover {
    cursor: pointer;
}
</style>